import { BaseConfig } from "./config"

var requireContext = require('node-require-context')
var fs = require('fs-extra')
var path = require('path')
import { InterfacePageJson } from '../entery/index';
export class ReactTsTool extends BaseConfig {
    allArr = []
    needLogin = []
    needPhone = []
    constructor(val: any) {
        super();
        try {
            this.init(val)
        } catch (error) {

        }
    }
    init(val: any) {
        const context = requireContext(val, true, /\.json$/)
        context.keys().forEach((moduleId: string, index: number) => {
            let str = context(moduleId) as never
            this.allArr.push(str);
        })
        this.writeRouterFile();
    }
    async writeAllPagePath() {
        fs.writeFile(path.join(__dirname, './router.json'), JSON.stringify(this.allArr, null, "\t")).then((err: any) => {
            if (err) {
                console.error(err)
            }
        })
    }
    async writeRouterFile() {
        let str = this.creactImportStr();
        let interFace = `interface Route { \r\tname: String,\r\tpath: String,\r\tloginAuth: Boolean,\r\tcomponent: Object \r}\r`
        str = str + interFace;
        let SignInRouters = this.creactSignArr();
        str = str + SignInRouters;

        fs.writeFile(path.join(__dirname, './pageRouter.ts'), str).then((err: any, res: any) => {
            console.log(err, res)
            if (err) {
                console.error(err)
            }
        })
    }
    creactImportStr() {
        let str = ""
        this.allArr.forEach((val: InterfacePageJson) => {
            str = str + `import ${val.name} from '@${val.component}';\r`

        })
        return str;
    }
    creactSignArr() {
        let str = ""
        this.allArr.forEach((val: InterfacePageJson) => {
            str += `\r\t{\r\t\tname: "${val.name}",\r\t\tpath: '${val.path}',\r\t\tloginAuth: ${val.config.loginAuth},\r\t\tcomponent: ${val.name},\r\t},\r`
        })
        let templateStr = `const SignInRouters : Route[] = [${str}]`
        return templateStr;
    }
}
